
const fs = require('fs')
const path = require('path')
const Router = require('koa-router')
const router = new Router()
const route = getRouter()

let prefixString = global.config.prefixString
if (prefixString.length>0) prefixString = "/" + prefixString

for (let i in route){
    const modulePath = path.resolve(__dirname,route[i].handler)
    eval(`router.${route[i].method}('${prefixString}${route[i].path}',  require('${modulePath}'))`)
}

//遍历 ./list 文件夹下所有路由文件
function getRouter() {
    // 定义要遍历的目录路径
    const directoryPath = path.resolve(__dirname,'./list')
    // 定义一个空数组来存储所有router的数组
    let allRouters =[]
    const dir  = fs.readdirSync(directoryPath) // 读取目录下所有文件
    for (let i in dir){
        const filePath = path.join(directoryPath, dir[i])
        const stats = fs.statSync(filePath) // 获取文件信息
        if (stats.isFile() && path.extname(filePath) === '.json') {
            const file = fs.readFileSync(filePath, 'utf-8')
            const jsonObject = JSON.parse(file)
            allRouters = allRouters.concat(jsonObject.routers)
        }
    }
    return allRouters
}

module.exports = router